package android.vstore.activities;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import DAO.NotificationDAO;
import DAO.ProductDAO;
import DTO.CategoryDTO;
import DTO.PInfo;
import DTO.TopicDTO;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.vstore.custom.AppSectionsPagerAdapter;
import android.vstore.fragment.PageSectionFragment;
import android.vstore.fragment.SceneHomeFragment;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import anroid.vstore.provider.Constant;
import anroid.vstore.provider.Helper;
import anroid.vstore.provider.Navigator;
import anroid.vstore.provider.SharedPreference;

import com.appvn2014.appstorevn.R;
import com.viewpagerindicator.TabPageIndicator;

@SuppressLint("NewApi")
public class MainActivity extends BaseActivity implements TabListener {

	// Number of noti of day
	protected static final int NOTIFICATION_COMING = 0;
	public static ArrayList<PInfo> _installed = null;
	public static ArrayList<CategoryDTO> _appcategories = new ArrayList<CategoryDTO>();
	public static ArrayList<CategoryDTO> _gamecategories;
	
	public static Boolean isCheckedNotification = false;

	public static int width;
	public static int height;
	public static Integer listnotf;
	
	private SceneHomeFragment home;
	private ViewPager vp_mainpager;
	private Thread _thread;
	
	private MenuItem mitem_notification;
	private TextView tv_notif_count;
	private FrameLayout fl_notiLay;
	private View v_count_lay;
	private ArrayList<Fragment> _lst_frags;
	
	@SuppressLint("ResourceAsColor")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		height = displaymetrics.heightPixels;
		width = displaymetrics.widthPixels;


        
        getSupportFragmentManager().beginTransaction().add(R.id.ll_main_root, SceneHomeFragment.newinstance(this)).commit();
		
        InitActionBar();

		overrideMessageHandler();
		
		(new Loader()).execute();
	}

	private void overrideMessageHandler() {
		_messageHandler = new Handler(){
			@Override
			public void handleMessage(Message msg)
			{
				if(msg.what == NOTIFICATION_COMING)
				{

					if(listnotf == 0 || MainActivity.isCheckedNotification)
						fl_notiLay.setVisibility(View.INVISIBLE);
					//					notification.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
					else
					{
						fl_notiLay.setVisibility(View.VISIBLE);
						//					notification.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
						tv_notif_count.setText(listnotf + "");
					}
				}
				if(msg.what == Constant.REFRESH_ALL_PAGE)
	    		{
					invalidatePages();
	    		}
			}
		};
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		invalidatePages();
	}
	public class Loader extends AsyncTask<Void, Void,Integer>{
		@Override
		protected Integer doInBackground(Void... params) {			
			return getIntent().getIntExtra("productID", -1);
		}      
		
		@Override
		protected void onPostExecute(Integer id) {
			if(id!= -1)
				Navigator.toDetailItem(MainActivity.this, id);
		}

		@Override
		protected void onPreExecute() {
			
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            return true;
        case R.id.action_notification:
        	MainActivity.isCheckedNotification= true;

			SharedPreference sharedpref = new SharedPreference(MainActivity.this);
			DateFormat df = new SimpleDateFormat("dd MM yyyy");
			Date currDate = Calendar.getInstance().getTime();
			sharedpref.setLastestDate(df.format(currDate));

			Intent intent = new Intent(MainActivity.this, SceneNotificationsActivity.class);
			startActivityForResult(intent,11);
        	return true;
        }
        return super.onOptionsItemSelected(item);
    }
	@SuppressLint("NewApi")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);

		v_count_lay = menu.findItem(R.id.action_notification).getActionView();
		
		v_count_lay.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MainActivity.isCheckedNotification= true;

				SharedPreference sharedpref = new SharedPreference(MainActivity.this);
				DateFormat df = new SimpleDateFormat("dd MM yyyy");
				Date currDate = Calendar.getInstance().getTime();
				sharedpref.setLastestDate(df.format(currDate));

				Intent intent = new Intent(MainActivity.this, SceneNotificationsActivity.class);
				startActivityForResult(intent,11);
			}
		});
		
		
		tv_notif_count = (TextView) v_count_lay.findViewById(R.id.tv_mainview_number_notification);
		fl_notiLay = (FrameLayout) v_count_lay.findViewById(R.id.fl_mainview_notification);
		//		count.setVisibility(View.INVISIBLE);
		//		
		if(isCheckedNotification)
			fl_notiLay.setVisibility(View.INVISIBLE	);
		mitem_notification = menu.findItem(R.id.action_notification);
		mitem_notification.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		Load();

		return true;
	}
	@Override
	public void onTabReselected(Tab arg0, android.app.FragmentTransaction arg1) {
		// TODO Auto-generated method stub

	}
	@SuppressLint("NewApi")
	@Override
	public void onTabSelected(Tab tab, android.app.FragmentTransaction arg1) {
		// TODO Auto-generated method stub
		vp_mainpager.setCurrentItem(tab.getPosition());

	}
	@Override
	public void onTabUnselected(Tab arg0, android.app.FragmentTransaction arg1) {
		// TODO Auto-generated method stub

	}
	
	public void Load()
	{
		if(_thread != null)
		{
			_thread.interrupt();
		}
		_thread = new Thread()
		{
			@Override
			public void run() {
				listnotf = NotificationDAO.NewNotification();
				_messageHandler.sendMessage(Message.obtain(_messageHandler, NOTIFICATION_COMING, 0, 0, listnotf));			
			}
		};
		_thread.start();	
	}
//	public Handler _messageHandler = new Handler(){
//		@Override
//		public void handleMessage(Message msg)
//		{
//			if(msg.what == NOTIFICATION_COMING)
//			{
//
//				if(listnotf == 0 || MainActivity.isCheckedNotification)
//					fl_notiLay.setVisibility(View.INVISIBLE);
//				//					notification.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
//				else
//				{
//					fl_notiLay.setVisibility(View.VISIBLE);
//					//					notification.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
//					tv_notif_count.setText(listnotf + "");
//				}
//			}
//			if(msg.what == PageSectionFragment.REFRESH_ALL_PAGE)
//    		{
//				invalidatePages();
//    		}
//		}
//	};
	private void invalidatePages() {
		for(int i =0; i < _lst_frags.size(); i++)
		{
			if(_lst_frags.get(i).getClass().equals(PageSectionFragment.class))
			{
//				_messageHandler.sendMessage(Message.obtain(_messageHandler, BITMAP_LIST_ALL_LOADED, 0, 0, null));
				((PageSectionFragment)_lst_frags.get(i))._messageHandler.sendMessage(Message.obtain(_messageHandler, Constant.REFRESH_ALL_PAGE, 0, 0, null));
			}

		}
	}
	private boolean doubleBackToExitPressedOnce= false;

	public boolean isConnectingToInternet(){
		ConnectivityManager connectivity = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) 
		{
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) 
				for (int i = 0; i < info.length; i++) 
					if (info[i].getState() == NetworkInfo.State.CONNECTED)
					{
						return true;
					}

		}
		return false;
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Check which request we're responding to
		// Make sure the request was successful
		if (resultCode == Constant.TYPE_ALL) {
			vp_mainpager.setCurrentItem(1);
			return;
		}
		if(requestCode == 11)
		{
			fl_notiLay.setVisibility(View.INVISIBLE);
		}

	}
	@Override
	public void onBackPressed() {
		if (doubleBackToExitPressedOnce) {
			super.onBackPressed();
			return;
		}

		this.doubleBackToExitPressedOnce = true;
		Toast.makeText(this, R.string.back_pressed, Toast.LENGTH_SHORT).show();

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				doubleBackToExitPressedOnce=false;                       
			}
		}, 2000);
	} 
	
}
